<template>
  <div class="produce-management">
    <div class="header">
      <h1>农产品管理</h1>
      <div class="batch-actions">
        <el-button type="primary" @click="showAddDialog = true">
          <i class="el-icon-plus"></i> 新增
        </el-button>
        <el-button @click="batchShelf(true)">
          <i class="el-icon-upload2"></i> 批量上架
        </el-button>
        <el-button @click="batchShelf(false)">
          <i class="el-icon-download"></i> 批量下架
        </el-button>
        <el-button @click="batchRecommend(true)">
          <i class="el-icon-star-on"></i> 批量推荐
        </el-button>
        <el-button @click="batchRecommend(false)">
          <i class="el-icon-close"></i> 批量取消推荐
        </el-button>
        <el-button @click="exportData">
          <i class="el-icon-document"></i> 导出
        </el-button>
      </div>
    </div>

    <!-- 搜索筛选区域 - 按照图片布局修正 -->
    <div class="search-form">
      <div class="form-grid">
        <!-- 第一行 -->
        <div class="form-row">
          <div class="form-item">
            <label>农产品名称</label>
            <el-input
              v-model="searchForm.name"
              placeholder="请输入农产品名称"
              clearable
            ></el-input>
          </div>
          <div class="form-item">
            <label>农产品类型</label>
            <el-select
              v-model="searchForm.type"
              placeholder="请选择"
              clearable
            >
              <el-option label="水果" value="水果"></el-option>
              <el-option label="蔬菜" value="蔬菜"></el-option>
              <el-option label="谷物" value="谷物"></el-option>
              <el-option label="肉类" value="肉类"></el-option>
              <el-option label="水产" value="水产"></el-option>
            </el-select>
          </div>
          <div class="form-item">
            <label>创建时间</label>
            <el-date-picker
              v-model="searchForm.createTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              style="width: 100%"
            >
            </el-date-picker>
          </div>
        </div>

        <!-- 第二行 -->
        <div class="form-row">
          <div class="form-item">
            <label>上架状态</label>
            <el-select
              v-model="searchForm.shelfStatus"
              placeholder="请选择状态"
              clearable
              style="width: 100%"
            >
              <el-option label="已上架" value="上架"></el-option>
              <el-option label="未上架" value="下架"></el-option>
            </el-select>
          </div>
          <div class="form-item">
            <label>是否推荐</label>
            <el-select
              v-model="searchForm.recommendStatus"
              placeholder="请选择状态"
              clearable
              style="width: 100%"
            >
              <el-option label="推荐" value="推荐"></el-option>
              <el-option label="不推荐" value="不推荐"></el-option>
            </el-select>
          </div>
          <div class="form-item">
            <!-- 第三个位置留空，与图片布局一致 -->
          </div>
        </div>
      </div>

      <div class="form-actions">
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </div>
    </div>

    <!-- 表格部分保持不变 -->
    <el-table
      :data="paginatedProducts"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
      @sort-change="handleSortChange"
      v-loading="loading"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="序号" width="80" />
      <el-table-column label="农产品图" width="120">
        <template #default="scope">
          <el-image
            v-if="scope.row.image"
            :src="scope.row.image"
            :preview-src-list="[scope.row.image]"
            style="width: 40px; height: 40px; border-radius: 4px;"
            fit="cover"
          />
          <div v-else class="empty-image">
            <i class="el-icon-picture-outline"></i>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="name"
        label="农产品名称"
        sortable="custom"
        :sort-orders="['ascending', 'descending']"
      />
      <el-table-column
        prop="merchant"
        label="商户名称"
        sortable="custom"
        :sort-orders="['ascending', 'descending']"
      />
      <el-table-column
        prop="type"
        label="农产品类型"
        sortable="custom"
        :sort-orders="['ascending', 'descending']"
      />
      <el-table-column
        prop="price"
        label="价格"
        width="120"
        sortable="custom"
        :sort-orders="['ascending', 'descending']"
      >
        <template #default="scope">
          ¥{{ scope.row.price }}
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="180"
        sortable="custom"
        :sort-orders="['ascending', 'descending']"
      />
      <el-table-column label="是否推荐" width="120">
        <template #default="scope">
          <el-tag :type="scope.row.recommended ? 'success' : 'info'" size="small">
            {{ scope.row.recommended ? '推荐' : '不推荐' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="上架状态" width="120">
        <template #default="scope">
          <el-tag :type="scope.row.status === '上架' ? 'success' : 'danger'" size="small">
            {{ scope.row.status === '上架' ? '已上架' : '未上架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <div class="text-buttons">
            <el-button
              type="text"
              size="mini"
              @click="shelfProduct(scope.row.id, scope.row.status === '上架' ? '下架' : '上架')"
              :class="{ 'active-text': scope.row.status !== '上架' }"
            >
              {{ scope.row.status === '上架' ? '下架' : '上架' }}
            </el-button>
            <el-button
              type="text"
              size="mini"
              @click="toggleRecommend(scope.row.id, !scope.row.recommended)"
              :class="{ 'active-text': !scope.row.recommended }"
            >
              {{ scope.row.recommended ? '取消推荐' : '推荐' }}
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <span class="total">共 {{ total }} 条记录</span>
      <el-pagination
        @current-change="changePage"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="prev, pager, next"
        :total="total"
      />
    </div>

    <!-- 添加农产品弹窗保持不变 -->
    <el-dialog
      title="添加农产品"
      :visible.sync="showAddDialog"
      width="600px"
    >
      <el-form :model="addForm" :rules="addFormRules" ref="addForm" label-width="100px">
        <el-form-item label="农产品名称" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入农产品名称"></el-input>
        </el-form-item>

        <el-form-item label="图片">
          <el-upload
            class="upload-demo"
            action="#"
            :on-change="handleImageChange"
            :auto-upload="false"
            :show-file-list="false"
            accept=".png,.jpg,.jpeg"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          <div class="upload-tip">请上传大小不超过5MB格式为png/jpg/jpeg的文件</div>
        </el-form-item>

        <el-form-item label="卖点摘要">
          <el-input
            type="textarea"
            v-model="addForm.summary"
            placeholder="请输入卖点摘要"
            :rows="3"
          ></el-input>
        </el-form-item>

        <el-form-item label="所属品类">
          <el-input v-model="addForm.category" placeholder="请输入所属品类"></el-input>
        </el-form-item>

        <el-form-item label="农产品类型">
          <el-select v-model="addForm.type" placeholder="请选择农产品类型" style="width: 100%">
            <el-option label="水果" value="水果"></el-option>
            <el-option label="蔬菜" value="蔬菜"></el-option>
            <el-option label="谷物" value="谷物"></el-option>
            <el-option label="肉类" value="肉类"></el-option>
            <el-option label="水产" value="水产"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="所属商户">
          <el-input v-model="addForm.merchant" placeholder="请输入所属商户"></el-input>
        </el-form-item>

        <el-form-item label="价格">
          <el-input v-model="addForm.price" placeholder="请输入价格">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>

        <el-form-item label="上架状态">
          <el-select v-model="addForm.status" placeholder="请选择上架状态" style="width: 100%">
            <el-option label="上架" value="上架"></el-option>
            <el-option label="下架" value="下架"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="是否推荐">
          <el-select v-model="addForm.recommended" placeholder="请选择是否推荐" style="width: 100%">
            <el-option label="推荐" value="推荐"></el-option>
            <el-option label="不推荐" value="不推荐"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="产品详情">
          <el-input
            type="textarea"
            v-model="addForm.detail"
            placeholder="请输入内容"
            :rows="4"
          ></el-input>
        </el-form-item>

        <el-form-item label="创建人">
          <el-input v-model="addForm.creator" placeholder="请输入创建人"></el-input>
        </el-form-item>

        <el-form-item label="浏览量">
          <el-input v-model="addForm.views" placeholder="请输入浏览量"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="submitAddForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      currentPage: 1,
      pageSize: 10,
      selectedRows: [],
      products: [],
      total: 0,
      loading: false,
      showAddDialog: false,
      sortParams: {
        prop: '',
        order: ''
      },
      // 搜索表单数据
      searchForm: {
        name: '',
        type: '',
        createTime: [],
        shelfStatus: '',
        recommendStatus: ''
      },
      // 添加农产品表单数据
      addForm: {
        name: '',
        image: null,
        summary: '',
        category: '',
        type: '',
        merchant: '',
        price: '',
        status: '',
        recommended: '',
        detail: '',
        creator: '',
        views: ''
      },
      // 表单验证规则（只保留农产品名称）
      addFormRules: {
        name: [
          { required: true, message: '请输入农产品名称', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    paginatedProducts() {
      return this.products
    }
  },
  created() {
    this.fetchProducts()
  },
  methods: {
    /**
     * 获取农产品列表
     */
    async fetchProducts() {
      this.loading = true
      try {
        const params = {
          page: this.currentPage,
          size: this.pageSize,
          ...this.searchForm
        }

        // 添加排序参数
        if (this.sortParams.prop) {
          params.sortField = this.sortParams.prop
          params.sortOrder = this.sortParams.order
        }

        const response = await this.$http.get('/api/products', { params })
        this.products = response.data.list
        this.total = response.data.total
      } catch (error) {
        console.error('获取农产品列表失败:', error)
        this.$message.error('获取农产品列表失败')
        this.products = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },

    /**
     * 表格排序变化
     */
    handleSortChange({ column, prop, order }) {
      this.sortParams = {
        prop: prop,
        order: order
      }
      this.currentPage = 1
      this.fetchProducts()
    },

    /**
     * 表格选择变化
     */
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },

    /**
     * 分页变化
     */
    changePage(page) {
      this.currentPage = page
      this.fetchProducts()
    },

    /**
     * 搜索相关方法
     */
    handleSearch() {
      this.currentPage = 1
      this.fetchProducts()
    },

    resetSearch() {
      this.searchForm = {
        name: '',
        type: '',
        createTime: [],
        shelfStatus: '',
        recommendStatus: ''
      }
      this.sortParams = {
        prop: '',
        order: ''
      }
      this.currentPage = 1
      this.fetchProducts()
    },

    /**
     * 添加农产品相关方法
     */
    handleImageChange(file) {
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过 5MB!');
        return;
      }
      this.addForm.image = file;
    },

    async submitAddForm() {
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          try {
            await this.$http.post('/api/products', this.addForm)
            this.$message.success('农产品添加成功');
            this.showAddDialog = false;
            this.resetAddForm();
            this.fetchProducts();
          } catch (error) {
            console.error('添加农产品失败:', error)
            this.$message.error('农产品添加失败');
          }
        } else {
          this.$message.error('请填写农产品名称');
          return false;
        }
      });
    },

    resetAddForm() {
      this.addForm = {
        name: '',
        image: null,
        summary: '',
        category: '',
        type: '',
        merchant: '',
        price: '',
        status: '',
        recommended: '',
        detail: '',
        creator: '',
        views: ''
      };
      if (this.$refs.addForm) {
        this.$refs.addForm.clearValidate();
      }
    },

    /**
     * 上架/下架商品
     */
    async shelfProduct(id, action) {
      try {
        await this.$http.put(`/api/products/${id}/status`, {
          status: action === '上架' ? 'ON' : 'OFF'
        })
        this.$message.success(`已${action}商品`)
        this.fetchProducts()
      } catch (error) {
        console.error(`${action}商品失败:`, error)
        this.$message.error(`${action}商品失败`)
      }
    },

    /**
     * 推荐/取消推荐商品
     */
    async toggleRecommend(id, recommend) {
      try {
        await this.$http.put(`/api/products/${id}/recommend`, {
          recommend
        })
        this.$message.success(`${recommend ? '推荐' : '取消推荐'}商品成功`)
        this.fetchProducts()
      } catch (error) {
        console.error(`${recommend ? '推荐' : '取消推荐'}商品失败:`, error)
        this.$message.error(`${recommend ? '推荐' : '取消推荐'}商品失败`)
      }
    },

    /**
     * 批量上架/下架
     */
    async batchShelf(isShelf) {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请先选择要操作的商品')
        return
      }

      const action = isShelf ? '上架' : '下架'
      this.$confirm(`确定要${action}选中的${this.selectedRows.length}个商品吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await this.$http.put('/api/products/batch-status', {
            ids: this.selectedRows.map(row => row.id),
            status: isShelf ? 'ON' : 'OFF'
          })
          this.$message.success(`已${action}${this.selectedRows.length}个商品`)
          this.selectedRows = []
          this.fetchProducts()
        } catch (error) {
          console.error(`批量${action}商品失败:`, error)
          this.$message.error(`批量${action}商品失败`)
        }
      }).catch(() => {})
    },

    /**
     * 批量推荐/取消推荐
     */
    async batchRecommend(isRecommend) {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请先选择要操作的商品')
        return
      }

      const action = isRecommend ? '推荐' : '取消推荐'
      this.$confirm(`确定要${action}选中的${this.selectedRows.length}个商品吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await this.$http.put('/api/products/batch-recommend', {
            ids: this.selectedRows.map(row => row.id),
            recommend: isRecommend
          })
          this.$message.success(`已${action}${this.selectedRows.length}个商品`)
          this.selectedRows = []
          this.fetchProducts()
        } catch (error) {
          console.error(`批量${action}商品失败:`, error)
          this.$message.error(`批量${action}商品失败`)
        }
      }).catch(() => {})
    },

    /**
     * 导出数据
     */
    async exportData() {
      try {
        const response = await this.$http.get('/api/products/export', {
          params: this.searchForm,
          responseType: 'blob'
        })

        const url = window.URL.createObjectURL(new Blob([response.data]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', `农产品数据_${new Date().getTime()}.xlsx`)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)

        this.$message.success('导出成功')
      } catch (error) {
        console.error('导出失败:', error)
        this.$message.error('导出失败')
      }
    }
  }
}
</script>

<style scoped>
.produce-management {
  background: white;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h1 {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.batch-actions {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

/* 搜索表单样式 - 按照图片布局修正 */
.search-form {
  background: white;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  border: 1px solid #e6e6e6;
}

.form-grid {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-row {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.form-item {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-width: 200px;
}

.form-item label {
  margin-bottom: 8px;
  color: #606266;
  font-size: 14px;
  font-weight: 500;
}

.form-actions {
  display: flex;
  gap: 10px;
  margin-top: 20px;
  justify-content: center;
}

/* 文本按钮样式 */
.text-buttons {
  display: flex;
  gap: 12px;
}

.text-buttons .el-button--text {
  padding: 0;
  color: #606266;
  font-size: 12px;
}

.text-buttons .el-button--text:hover {
  color: #409EFF;
}

.text-buttons .active-text {
  color: #409EFF;
  font-weight: 500;
}

/* 弹窗表单样式 */
.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.dialog-footer {
  text-align: right;
  margin-top: 20px;
}

.empty-image {
  width: 40px;
  height: 40px;
  background-color: #f5f7fa;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #c0c4cc;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total {
  color: #606266;
  font-size: 14px;
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .batch-actions {
    width: 100%;
    justify-content: flex-start;
  }

  .pagination {
    flex-direction: column;
    gap: 15px;
  }

  .form-row {
    flex-direction: column;
    gap: 15px;
  }

  .form-item {
    min-width: 100%;
  }

  .text-buttons {
    flex-direction: column;
    gap: 8px;
  }
}
</style>
